package com.fengye.algorithms.leecode;

/**
 * @Author fengye
 * @Date 2023/4/8 9:43
 **/
public class MyAtoi08 {
    public int myAtoi(String s) {
        if(s.equals("") || s.equals("-")||s.equals("+")) {
            return 0;
        }
        int i = 0;
        for (; i <s.length();i++){
            char c = s.charAt(i);
            if(c != ' '){
                break;
            }
        }

        if(i> 0){
            s = s.substring(i);
        }
        if(s.equals("")) {
            return 0;
        }

        StringBuilder sb = new StringBuilder();
        if(s.charAt(0) == '-'){
            s = s.substring(1);
            sb.append('-');
        } else if(s.charAt(0) == '+') {
            s = s.substring(1);
        }

        if(s.equals("")) {
            return 0;
        }

        for(int j = 0; j < s.length();j++) {
            if(Character.isDigit(s.charAt(j))) {
                sb.append(s.charAt(j));
            } else {
                break;
            }
        }

        String sr = sb.toString();
        if(sr.equals("") || sr.equals("-")) {
            return 0;
        }

        double l = Double.parseDouble(sb.toString());
        int res = 0;
        if(l > Integer.MAX_VALUE) {
            res = Integer.MAX_VALUE;
        } else if(l < Integer.MIN_VALUE){
            res = Integer.MIN_VALUE;
        } else {
            res = (int)l;
        }
        return res;
    }
}
